package _spring_test._DataBinder;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.validation.DataBinder;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class DataToBeanUtil {

    //excel
    public static <T> List<T> dataToBean(List<List<Object>> list, Class<T> clazz) throws IllegalAccessException, InstantiationException {
        if(list==null || list.isEmpty()){
            //todo..
        }

        List<T> tList = new ArrayList<>();

        Field[] fields = clazz.getDeclaredFields();

        for(int i=0; i<list.size(); i++){
            List<Object> object1s = list.get(i);
            if(list==null || list.isEmpty()){
                //todo..
            }
            T t = clazz.newInstance();
            DataBinder dataBinder = new DataBinder(t);
            MutablePropertyValues mpv = new MutablePropertyValues();
            for(int j=0; j<object1s.size(); j++){
                Object obj = object1s.get(j);
                String fieldName = fields[j].getName();
                mpv.addPropertyValue(fieldName, obj);
            }
            dataBinder.bind(mpv);
            tList.add(t);
        }

        return tList;
    }


    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        System.out.println(111);

        List<List<Object>> list = new ArrayList<>();
        List<Object> object1s = new ArrayList<>();
        object1s.add("11");
        object1s.add("12");
        object1s.add("13");
        object1s.add("14");
        List<Object> object2s = new ArrayList<>();
        object2s.add("21");
        object2s.add("22");
        object2s.add("23");
        object2s.add("24");
        List<Object> object3s = new ArrayList<>();
        object3s.add("31");
        object3s.add("32");
        object3s.add("33");
        object3s.add("34");

        list.add(object1s);
        list.add(object2s);
        list.add(object3s);

        List<Product> products = DataToBeanUtil.dataToBean(list, Product.class);

        System.out.println(222);
    }
}
